import time
from copy import deepcopy
import arrow
from flask import Blueprint, request

from db_init import db
from tools.tools import my_route, old_limit, item2dict
from config import DAY_S
from model.model import House, Order, Role, Power, User, user_role

back = Blueprint('back', __name__)


@back.route('/statistics/occupancy')
def occupancy():
    print(1)
    year_now = arrow.now().year
    start_t = arrow.get(f'{year_now}-01-01 00:00:00', 'YYYY-MM-DD HH:mm:ss')
    end_t = arrow.get(f'{year_now}-12-31 24:00:00', 'YYYY-MM-DD HH:mm:ss')
    interval = end_t - start_t
    total = House.query.count() * interval.days
    orders = Order.query.filter(Order.start_t < end_t.int_timestamp, Order.end_t > start_t.int_timestamp).all()
    days = 0
    for order in orders:
        days += (order.end_t - order.start_t) // DAY_S

    return f'{time.time()}'


@back.route('/role', methods=['POST'])
def add_role():
    return f'{time.time()}'


@back.route('/power', methods=['POST'])
def add_power():
    db.session.add(Power(**dict(request.json)))
    db.session.commit()
    return my_route(200)


@back.route('/role', methods=['GET'])
def get_role():
    offset, limit = old_limit(dict(request.args))
    return my_route(200, item2dict(Role.query.limit(limit).offset(offset).all()))


@back.route('/role', methods=['PUT'])
def put_role():
    role_id = request.json.get('role_id')
    power_ids = request.json.get('power_ids')
    role = Role.query.get(role_id)
    powers = Power.query.filter(Power.id.in_(power_ids)).all()

    print(role, "22222222")
    print(role.power)

    role.power = powers
    ret_data = deepcopy(role)
    db.session.commit()

    return my_route(200, item2dict(ret_data))


@back.route('/user/role', methods=['PUT'])
def put_user_role():
    old_role_id = request.json.get('old_role_id')
    new_role_id = request.json.get('new_role_id')
    user_id = request.json.get('user_id')
    # role = Role.query.get(role_id)
    # add_role = Role.query.get(1)
    # user = User.query.get(user_id)
    # user.roles.remove(role)
    # user.roles.append(add_role)

    db.session.query(user_role).filter_by(user_id=user_id, role_id=old_role_id).update({'role_id': new_role_id})
    db.session.commit()
    return my_route(200, "item2dict(role)")
